package spar.cancer.algorithm.invgen;

import java.io.File;
import java.io.IOException;

public class InvGenDaikon implements InvGen{
    private static final String ROOT_DTRACE_DIR = "output/grouptrace/";
    private static final String ROOT_INV_DIR = "output/inv/";
    private final String daikonPath;
    private final String rootDtraceDir;
    private final String rootInvDir;

    public InvGenDaikon(String daikonPath, String subDtraceDir, String subInvDir) {
        this.daikonPath = daikonPath;
        this.rootDtraceDir = ROOT_DTRACE_DIR + subDtraceDir;
        this.rootInvDir = ROOT_INV_DIR + subInvDir;
    }

    public InvGenDaikon(String daikonPath, String subDtraceDir) {
        this(daikonPath, subDtraceDir, subDtraceDir);
    }

    private void run(String subDtraceDir) throws IOException {
        File dir = new File(rootDtraceDir + subDtraceDir);

        for (File file : dir.listFiles()) {
            if (file.isFile() && file.getName().matches("(.*)\\.dtrace")) {
                String dtracePath = rootDtraceDir + subDtraceDir + "/" + file.getName();
                String declsPath = rootDtraceDir + subDtraceDir + "/" +
                        file.getName().replaceAll("\\.dtrace", ".decls");
                String invDir = rootInvDir + subDtraceDir;
                new File(invDir).mkdirs();
                String invPath = invDir + "/" +
                        file.getName().replaceAll("\\.dtrace", ".inv");
                String invgzPath = invPath.replaceAll("\\.inv", ".inv.gz");
                String daikonCmd = "java -cp " + daikonPath +
                        " daikon.Daikon -o " + invgzPath + " " +
                        dtracePath + " " + declsPath + " > " + invPath;
                String[] cmd = new String[]{"cmd", "/c", daikonCmd};
                Runtime.getRuntime().exec(cmd);
            } else if (file.isDirectory()) {
                run(subDtraceDir + "/" + file.getName());
            }
        }
    }

    @Override
    public void run() throws IOException {
        run("");
    }
}
